package hlhj.fhp.burst.activitys

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.tenma.ventures.base.TMActivity
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import hlhj.fhp.burst.*
import hlhj.fhp.burst.adapter.CommentAdp
import hlhj.fhp.burst.adapter.CommentAdp2
import hlhj.fhp.burst.adapter.NineGridAdp
import hlhj.fhp.burst.bean.BaseBean
import hlhj.fhp.burst.bean.BurstListBean
import hlhj.fhp.burst.bean.MyBurstBean
import hlhj.fhp.burst.camera.util.LogUtil
import hlhj.fhp.burst.customView.EditPop
import hlhj.fhp.burst.customView.LoadingDialog
import hlhj.fhp.burst.ninegrid.ImageInfo
import hlhj.fhp.burst.ninegrid.NineGridView
import hlhj.fhp.burst.ninegrid.preview.NineGridViewClickAdapter
import kotlinx.android.synthetic.main.activity_my_burst_aty.*
import kotlinx.android.synthetic.main.my_head.view.*
import java.util.ArrayList

class MyBurstAty : TMActivity(), SpringView.OnFreshListener {
    private var page=1
    private lateinit var  loadingDialog:LoadingDialog
    private lateinit var adp:BaseQuickAdapter<MyBurstBean.DataBean,BaseViewHolder>
    private val datas=ArrayList<MyBurstBean.DataBean>()
    private lateinit var headView:View
    private lateinit var goLoginDialog:GoLoginDialog
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_burst_aty)
        if (null!=TMSharedPUtil.getTMThemeColor(this)&&TMSharedPUtil.getTMThemeColor(this).length>0){
            loTittle.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this)))
        }
        loadingDialog= LoadingDialog(this)
        goLoginDialog= GoLoginDialog(this)
        goLoginDialog.setListener(object :GoLoginDialog.OnCancelListener{
            override fun cancle() {
                finish()
            }

            override fun yes() {
                finish()
            }
        })
        initView()
        initListener()
    }

    private fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
    }

    private fun initView() {
        initSp()
        headView=LayoutInflater.from(this).inflate(R.layout.my_head,null)
        if (!TextUtils.isEmpty(TMSharedPUtil.getTMThemeColor(this@MyBurstAty))){
            val drawable = headView.btGoBurst.background as GradientDrawable
            drawable.setStroke(2,Color.parseColor(TMSharedPUtil.getTMThemeColor(this@MyBurstAty)))
            headView.btGoBurst.background=drawable
            headView.btGoBurst.setTextColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this@MyBurstAty)))
        }
        headView.btGoBurst.setOnClickListener {
            val intent = Intent(this@MyBurstAty, ToBurstAty::class.java)
            startActivity(intent)
        }
        adp=object :BaseQuickAdapter<MyBurstBean.DataBean,BaseViewHolder>(R.layout.burst_item,datas){
            override fun convert(helper: BaseViewHolder?, item: MyBurstBean.DataBean?) {
                LogUtil.e("info",Contents.PUBLICK_URL+item?.iconName?.replace("\\","/"))
                item?.head_pic?.let {
                    if (it.contains("http")){
                        Glide.with(mContext).load(it.replace("\\","/"))
                                .apply(GlideUtil.loadHeadOption())
                                .into(helper?.getView(R.id.userIcon)!!)
                    }else{
                        Glide.with(mContext).load(Contents.PUBLICK_URL+"/"+it.replace("\\","/"))
                                .apply(GlideUtil.loadHeadOption())
                                .into(helper?.getView(R.id.userIcon)!!)
                    }
                }


                if (null==item?.member_nickname||item?.member_nickname.isEmpty()){
                    helper?.setText(R.id.userName,item?.member_name)
                }else{
                    helper?.setText(R.id.userName,item?.member_nickname)
                }
                helper?.setText(R.id.tvContent,item?.content)
                helper?.setText(R.id.btZan,item?.laud_num.toString())
                if (null==item?.address||item?.address.equals("")||item?.address.equals("0")){
                    helper?.setText(R.id.tvHowLong, TimeUtils.convertTimeToFormat(item?.create_at?.toLong()!!))
                }else{
                    helper?.setText(R.id.tvHowLong, TimeUtils.convertTimeToFormat(item?.create_at?.toLong()!!)+"发布于"+item?.address)
                }
                val nineGridView = helper?.getView<NineGridView>(R.id.nineGrideView)
                val btCheckAllContent = helper?.getView<TextView>(R.id.btCheckAllContent)
                if (item?.content?.length!!>70){
                    btCheckAllContent?.visibility= View.VISIBLE
                    btCheckAllContent?.setOnClickListener {
                        btCheckAllContent.maxLines=20
                    }
                }else{
                    btCheckAllContent?.visibility= View.GONE
                }
                val btCheckAll = helper?.getView<TextView>(R.id.btCheckAll)
                val thumbLo = helper?.getView<RelativeLayout>(R.id.thumbLo)
                val imgThumb = helper?.getView<ImageView>(R.id.imgThumb)
                val btComment = helper?.getView<ImageView>(R.id.btComment)
                val btZan = helper?.getView<TextView>(R.id.btZan)
                val btShare = helper?.getView<ImageView>(R.id.btShare)
                /*分享*/
                btShare!!.setOnClickListener {
                    val share = TMLinkShare()
                    share.description="${item?.content}"
                    share.title="爆料"
                    if (item?.source_type==1){
                        if (item?.source.size>0){
                            share.thumb=Contents.PUBLICK_URL+item?.source[0]
                        }
                    }else{
                        share.thumb=Contents.PUBLICK_URL+item?.video_thumb
                    }
                    share.url="${Contents.PUBLICK_URL}/application/hlhjburst/asset/index.htm?id=${item?.id}"
                    TMShareUtil.getInstance(mContext).shareLink(share)
                }
                /*点赞*/
                if (item?.is_laud==1){
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }else{
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }
                btZan?.setOnClickListener {
                    OkGo.get<String>(Contents.PUBLICK_URL+Contents.DIANZAN)
                            .params("token",TMSharedPUtil.getTMToken(this@MyBurstAty))
                            .params("burst_id",item?.id)
                            .execute(object :StringCallback(){
                                override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                    super.onStart(request)
                                    loadingDialog.show()
                                }
                                override fun onSuccess(response: Response<String>?) {
                                    loadingDialog.dismiss()
                                    val body = response?.body()
                                    val baseBean = Gson().fromJson(body!!, BaseBean::class.java)
                                    if (baseBean.code==1){
                                        if (item?.is_laud==1){
                                            btZan.text = (btZan.text.toString().toInt()-1).toString()
                                            item?.is_laud=0
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }else{
                                            btZan.text = (btZan.text.toString().toInt()+1).toString()
                                            item?.is_laud=1
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }
                                    }else if (baseBean.code==500){
                                        if (!goLoginDialog.isShowing){
                                            goLoginDialog.show()
                                        }
                                    }
                                }
                            })
                }
                /*评论*/
                btComment?.setOnClickListener {
                    EditPop(mContext,item?.id.toString(),"0",object : EditPop.CommentSuccessListener{
                        override fun commmentSuccess(str:String,id:String) {
                            val bean = MyBurstBean.DataBean.CommentBean()
                            bean.id=id.toInt()
                            bean.one_member_name=TMSharedPUtil.getTMUser(mContext).member_name
                            bean.one_member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                            bean.one_content=str
                            datas[helper?.adapterPosition-1].comment.add(bean)
                            notifyDataSetChanged()
                        }
                    }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                }
                /*资源加载*/
                val nineRcy = helper?.getView<RecyclerView>(R.id.nineRcy)

                if (item?.source_type==1){
                    thumbLo?.visibility=View.GONE
                    if (item?.source.size>0){
                        nineRcy?.visibility=View.VISIBLE
                        val nineAdp= NineGridAdp(item?.source as ArrayList<String>)
                        val manager = GridLayoutManager(mContext, 3)
                        manager?.isAutoMeasureEnabled=true
                        nineRcy.layoutManager= manager
                        nineRcy.adapter=nineAdp

                        nineAdp?.setOnItemClickListener { adapter, view, position ->
                            val intent = Intent(mContext, PreviewAtyBurst::class.java)
                            intent.putExtra("imgs", item?.source as ArrayList<String>)
                            startActivity(intent)
                        }
                    }else{
                        nineRcy?.visibility=View.GONE
                    }
                }else if (item?.source_type==2){
                    thumbLo?.visibility=View.VISIBLE
                    nineRcy?.visibility=View.GONE
                    thumbLo?.setOnClickListener {
                        val intent = Intent(mContext!!, VideoPlayAty::class.java)
                        intent.putExtra("url",item?.source[0])
                        intent.putExtra("img",Contents.PUBLICK_URL+item?.video_thumb)
                        startActivity(intent)
                    }

                    GlideUtil.loadImg(mContext,item?.video_thumb,imgThumb)

                }else{
                    nineRcy?.visibility=View.GONE
                    thumbLo?.visibility=View.GONE
                }

                if (item?.comment.size>0){
                    if (item?.comment.size>3){

                        btCheckAll?.visibility= View.VISIBLE
                        val tempDatas=ArrayList<MyBurstBean.DataBean.CommentBean>()
                        tempDatas.add(0,item?.comment[0])
                        tempDatas.add(0,item?.comment[1])
                        tempDatas.add(0,item?.comment[2])
                        val adp = CommentAdp2(mContext,tempDatas)
                        val myListView = helper?.getView<MyListView>(R.id.commentListView)
                        myListView?.adapter=adp
                        btCheckAll?.setOnClickListener {
                            val intent = Intent(mContext, BurstDetailAty::class.java)
                            intent.putExtra("type","2")
                            intent.putExtra("bean",item!!)
                            startActivity(intent)
                        }
                        myListView?.setOnItemClickListener { parent, view, position, id ->
                            EditPop(mContext,item?.id.toString(),tempDatas[position].id.toString(),object :EditPop.CommentSuccessListener{
                                override fun commmentSuccess(str:String,id:String) {
                                    val bean = MyBurstBean.DataBean.CommentBean()
                                    bean.id=id.toInt()
                                    bean.member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                                    bean.member_name=TMSharedPUtil.getTMUser(mContext).member_name
                                    if (null==tempDatas[position].member_name||tempDatas[position].member_name.isEmpty()){
                                        bean.one_member_name=tempDatas[position].one_member_name
                                        bean.one_member_nickname=tempDatas[position].one_member_nickname

                                    }else{
                                        bean.one_member_name=tempDatas[position].member_name
                                        bean.one_member_nickname=tempDatas[position].member_nickname
                                    }
                                    bean.content=str
                                    bean.one_content=str
                                    datas[helper?.adapterPosition-1].comment.add(bean)
                                    notifyDataSetChanged()
                                }
                            }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                        }
                    }else if (item?.comment.size==0){
                        btCheckAll?.visibility= View.GONE
                        val tempDatas=ArrayList<MyBurstBean.DataBean.CommentBean>()
                        val adp = CommentAdp2(mContext,tempDatas)
                        val myListView = helper?.getView<MyListView>(R.id.commentListView)
                        myListView?.adapter=adp
                    } else{
                        btCheckAll?.visibility= View.GONE
                        val adp = CommentAdp2(mContext,item?.comment as ArrayList<MyBurstBean.DataBean.CommentBean>)
                        val myListView = helper?.getView<MyListView>(R.id.commentListView)
                        myListView?.adapter=adp
                        myListView?.setOnItemClickListener { parent, view, position, id ->
                            EditPop(mContext,item?.id.toString(),item.comment[position].id.toString(),object :EditPop.CommentSuccessListener{
                                override fun commmentSuccess(str:String,id:String) {
                                    val bean = MyBurstBean.DataBean.CommentBean()
                                    bean.id=id.toInt()
                                    bean.member_nickname=TMSharedPUtil.getTMUser(mContext).member_real_name
                                    bean.member_name=TMSharedPUtil.getTMUser(mContext).member_name
                                    if (null==item?.comment[position].member_name||item?.comment[position].member_name.isEmpty()){
                                        bean.one_member_name=item?.comment[position].one_member_name
                                        bean.one_member_nickname=item?.comment[position].one_member_nickname

                                    }else{
                                        bean.one_member_name=item?.comment[position].member_name
                                        bean.one_member_nickname=item?.comment[position].member_nickname
                                    }
                                    bean.content=str
                                    bean.one_content=str
                                    datas[helper?.adapterPosition-1].comment.add(bean)
                                    notifyDataSetChanged()
                                }
                            }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)
                        }
                    }
                }else{
                    btCheckAll?.visibility= View.GONE
                    val tempDatas=ArrayList<MyBurstBean.DataBean.CommentBean>()
                    val adp = CommentAdp2(mContext,tempDatas)
                    val myListView = helper?.getView<MyListView>(R.id.commentListView)
                    myListView?.adapter=adp
                }
            }
        }
        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,false)
//        adp.setEmptyView(R.layout.emptyimg,recyclerview)
        adp.addHeaderView(headView)

    }

    private fun initSp() {
        spView.header=DefaultHeader(this)
        spView.footer=DefaultFooter(this)

        spView.setListener(this)
    }

    private fun getData() {
        OkGo.get<String>(Contents.PUBLICK_URL + Contents.MYBUrst)
                .params("token", TMSharedPUtil.getTMToken(this@MyBurstAty))
                .headers("token", TMSharedPUtil.getTMToken(this@MyBurstAty))
                .params("page", page)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        loadingDialog.show()
                    }
                    override fun onSuccess(response: Response<String>?) {
                        spView.onFinishFreshAndLoad()
                        LogUtil.i("okgo","OKle ?")
                        loadingDialog.dismiss()
                        val str = response?.body()
                        val bean = Gson().fromJson(str, MyBurstBean::class.java)
                        if (bean?.code==1){
                            LogUtil.i("okgo","OKle！！ ?")
                            if (page==1){
                                datas.clear()
                            }
                            datas.addAll(bean?.data)
                            adp.notifyDataSetChanged()
                        }else if (bean?.code==500){
                            if (!goLoginDialog.isShowing){
                                goLoginDialog.show()
                            }
                        }
                    }
                })
    }

    override fun onLoadmore() {
        page++
        getData()
    }

    override fun onResume() {
        super.onResume()
        page=0
        datas.clear()
        getData()
    }
    override fun onRefresh() {
        page=0
        datas.clear()
        getData()
    }
}
